<template>
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item class="smart-query-form-item" label="机器信息">
        <a-input v-model:value="queryForm.keyword" placeholder="请输入机器编码/序列号/IMEI" style="width: 260px"/>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="型号">
        <a-input v-model:value="queryForm.modelName" placeholder="请输入机器型号" style="width: 200px"/>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="库存状态">
        <a-select v-model:value="queryForm.status"
                  allowClear placeholder="全部" style="width: 100px">
          <a-select-option :value="0">正常</a-select-option>
          <a-select-option :value="1">冻结</a-select-option>
          <a-select-option :value="2">已出库</a-select-option>
          <a-select-option :value="3">待出库</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="渠道占用">
        <a-select v-model:value="queryForm.occupyChannel"
                  allowClear placeholder="全部" style="width: 160px">
          <a-select-option :value="1">回收占用</a-select-option>
          <a-select-option :value="2">第三方渠道占用</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="仓储区">
        <a-select v-model:value="queryForm.storageId" :field-names="{label: 'storageName',value: 'id'}"
                  :options="storageAreaOptions"
                  allowClear
                  placeholder="全部" style="width: 160px" @change="storageAreaChange">
        </a-select>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="货架">
        <a-select v-model:value="queryForm.storageRackId"
                  :field-names="{label: 'rackName',value: 'id'}"
                  :options="storageRackOptions"
                  allowClear placeholder="全部" style="width: 160px">
        </a-select>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="所属品牌">
        <a-select v-model:value="queryForm.brandId"
                  :field-names="{label: 'brandName',value: 'id'}"
                  :options="brandOptions"
                  allowClear placeholder="全部" style="width: 160px">
        </a-select>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="所属品类">
        <a-select v-model:value="queryForm.category"
                  allowClear placeholder="全部" style="width: 160px">
          <a-select-option :value="0">手机</a-select-option>
          <a-select-option :value="1">平板</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item class="smart-query-form-item smart-margin-left10">
        <a-button type="primary" @click="resetPageNumAjaxQuery">
          <template #icon>
            <SearchOutlined/>
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery">
          <template #icon>
            <ReloadOutlined/>
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>

  <a-card :bordered="false" :hoverable="true" size="small">
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button size="small" type="primary" @click="editRack()">
          修改货架
        </a-button>
        <a-button size="small" type="primary" @click="occupyChannel()">
          第三方销售平台占用
        </a-button>
        <a-button size="small" type="danger" @click="cancelOccupyChannel()">
          取消占用
        </a-button>
      </div>
    </a-row>

    <a-table
        :columns="columns"
        :dataSource="tableData"
        :loading="tableLoading"
        :pagination="false"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: rowSelectionChange }"
        :scroll="{ x: 1300 }"
        bordered
        rowKey="id"
        size="small"
    >
      <template #bodyCell="{ column, record, text }">

        <template v-if="column.dataIndex === 'storageName'">
          {{ text || '-' }}
        </template>
        <template v-if="column.dataIndex === 'rackName'">
          {{ text || '-' }}
        </template>
        <template v-if="column.dataIndex === 'modelName'">
          {{ text || '-' }}
        </template>
        <template v-if="column.dataIndex === 'occupyChannel'">
          {{ OCCUPYCHANNEL[text] }}
        </template>
        <template v-if="column.dataIndex === 'status'">
          {{ STATUS[text] }}
        </template>
        <template v-if="column.dataIndex === 'orderKey'">
          <a-button type="link" @click="toOrderDetail(record)">{{ text }}</a-button>
        </template>

        <template v-if="column.dataIndex === 'operate'">
          <div class="smart-table-operate">
            <a-button type="link" @click="previewDevice(record)">查看</a-button>
            <a-button type="link" @click="printDeviceInfo(record)">打印标签</a-button>
            <!--            <a-button danger type="link" @click="confirmDelete(record)">删除</a-button>-->
          </div>
        </template>
      </template>
    </a-table>

    <div class="smart-query-table-page">
      <a-pagination
          v-model:current="queryForm.pageNum"
          v-model:pageSize="queryForm.pageSize"
          :defaultPageSize="queryForm.pageSize"
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :show-total="(total) => `共${total}条`"
          :total="total"
          show-less-items
          showQuickJumper
          showSizeChanger
          @change="ajaxQuery"
          @showSizeChange="ajaxQuery"
      />
    </div>
  </a-card>

  <!--  机器详情-->
  <a-modal :footer="null" :visible="deviceInfoModal.visible" title="机器详情" width="600px"
           @cancel="hideDeviceInfoModal">
    <a-row>
      <a-col :span="6" style="text-align: right">型号：</a-col>
      <a-col :span="18">{{ deviceInfoModal.modelName }}</a-col>
    </a-row>
    <a-row>
      <a-col :span="6" style="text-align: right">所属品类：</a-col>
      <a-col :span="18">{{ deviceInfoModal.category == 1 ? '手机' : '平板' }}</a-col>
    </a-row>
    <a-row>
      <a-col :span="6" style="text-align: right">所属品牌：</a-col>
      <a-col :span="18">{{ deviceInfoModal.brandName }}</a-col>
    </a-row>
    <a-row>
      <a-col :span="6" style="text-align: right">机器编码：</a-col>
      <a-col :span="18">{{ deviceInfoModal.machineCode }}</a-col>
    </a-row>
    <a-row>
      <a-col :span="6" style="text-align: right">序列号：</a-col>
      <a-col :span="18">{{ deviceInfoModal.serialNumber }}</a-col>
    </a-row>
    <a-row>
      <a-col :span="6" style="text-align: right">仓储区：</a-col>
      <a-col :span="18">{{ deviceInfoModal.storageName }}</a-col>
    </a-row>
    <a-row>
      <a-col :span="6" style="text-align: right">货架：</a-col>
      <a-col :span="18">{{ deviceInfoModal.rackName }}</a-col>
    </a-row>
    <a-row>
      <a-col :span="6" style="text-align: right">库存状态：</a-col>
      <a-col :span="18">{{ STATUS[deviceInfoModal.status] }}</a-col>
    </a-row>
    <a-row>
      <a-col :span="6" style="text-align: right">渠道占用：</a-col>
      <a-col :span="18">{{ OCCUPYCHANNEL[deviceInfoModal.occupyChannel] }}</a-col>
    </a-row>
    <a-row>
      <a-col :span="6" style="text-align: right">关联订单：</a-col>
      <a-col :span="18"><a type="link" @click="toOrderList()">{{ deviceInfoModal.orderKey }}</a></a-col>
    </a-row>
    <a-row>
      <a-col :span="6" style="text-align: right">订单状态：</a-col>
      <a-col :span="18">{{ ORDERSTATUS[deviceInfoModal.ostat] }}</a-col>
    </a-row>
  </a-modal>


  <!--  修改货架-->
  <a-modal :title="`修改货架`" :visible="storageRackModal.visible" @cancel="hideStorageRackModal" @ok="changeStorageRack">
    <div style="margin-bottom: 8px">
      <span style="width: 80px;display: inline-block;text-align: right;margin-right: 8px"><span style="color: red">*</span>仓储区：</span>
      <a-select v-model:value="storageRackModal.storageId" :field-names="{label: 'storageName',value: 'id'}"
                :options="storageAreaOptions"
                allowClear
                placeholder="选择仓储区" style="width: 260px" @change="storageAreaChangeForModal">
      </a-select>
    </div>
    <div>
      <span style="width: 80px;display: inline-block;text-align: right;margin-right: 8px"><span style="color: red">*</span>货架：</span>
      <a-select v-model:value="storageRackModal.storageRackId"
                :field-names="{label: 'rackName',value: 'id'}"
                :options="storageRackOptionsForModal"
                allowClear placeholder="选择货架" style="width: 260px">
      </a-select>
    </div>

  </a-modal>

  <printer ref="printerRef"></printer>
</template>


<script setup>
import {PAGE_SIZE, PAGE_SIZE_OPTIONS} from "/@/constants/common-const";
import {nextTick, onMounted, reactive, ref} from "vue";
import {smartSentry} from "/@/lib/smart-sentry";
import {TABLE_ID_CONST} from "/@/constants/support/table-id-const";
import TableOperator from "/@/components/support/table-operator/index.vue";
import {message, Modal} from "ant-design-vue";
import {SmartLoading} from '/@/components/framework/smart-loading';
import {useRoute, useRouter} from 'vue-router';
import _ from "lodash";
import {inventoryApi} from "/@/views/business/storage/inventory";
import {storageAreaApi} from "/@/views/business/storage/storage-area";
import {storageRackApi} from "/@/views/business/storage/storage-rack";
import {brandApi} from "/@/views/business/data-config/brand/brand-api";
import Printer from "/@/views/business/printer/printer.vue";
import {STATUS as ORDERSTATUS} from "/@/views/business/order/order";

const printerRef = ref();
const router = useRouter();
const route = useRoute();
const OCCUPYCHANNEL = {
  0: '未占用', 1: '回收占用', 2: '第三方渠道占用'
}

const STATUS = {
  0: '正常', 1: '冻结 ', 2: '已出库', 3: '待出库'
}

const columns = ref([
  {
    align: 'center',
    title: '机器编码',
    dataIndex: 'machineCode',
    width: 160,
  },
  {
    align: 'center',
    title: '库存状态',
    dataIndex: 'status',
    width: 100,
  },
  {
    align: 'center',
    title: '渠道占用',
    dataIndex: 'occupyChannel',
    width: 120,
  },
  {
    align: 'center',
    title: '仓储区',
    dataIndex: 'storageName',
    ellipsis: true,
    width: 120,
  },
  {
    align: 'center',
    title: '货架',
    dataIndex: 'rackName',
    width: 120,
    ellipsis: true,
  },
  {
    align: 'center',
    title: '型号',
    dataIndex: 'modelName',
    width: 200,
    ellipsis: true,
  },
  {
    align: 'center',
    title: '成本价',
    dataIndex: 'price',
    width: 80,
  },
  {
    align: 'center',
    title: '关联订单编号',
    dataIndex: 'orderKey',
    width: 180,
  },
  {
    align: 'center',
    title: '入库时间',
    dataIndex: 'warehouseTime',
    width: 180,
  },
  {
    align: 'center',
    title: '操作',
    dataIndex: 'operate',
    width: 180,
    fixed: 'right'
  },
]);
// 组件ref
const formRef = ref();
const labelCol = {style: {width: '150px'}};
const wrapperCol = {span: 14};
const rules = {
  storageName: [{required: true, message: ''}],
};
let iconImgList = reactive({arr: []});
let quotationImgList = reactive({arr: []});
let modalVisible = ref(false);
const formDataDefault = {
  id: undefined,
  storageName: undefined,
  bak: '',
};

let formData = reactive({...formDataDefault});

const queryFormDataDefault = {
  keyword: undefined,
  modelName: undefined,
  status: undefined,
  occupyChannel: undefined,
  storageId: undefined,
  storageRackId: undefined,
  brandId: undefined,
  category: undefined,
  pageNum: 1,
  pageSize: PAGE_SIZE,
};
const queryForm = reactive({...queryFormDataDefault});
const tableLoading = ref(false);
const tableData = ref([]);
const total = ref();

const storageAreaOptions = ref([]);
const storageRackOptions = ref([]);
const brandOptions = ref([]);
let selectedRows = [];
const selectedRowKeys = ref([]);

const deviceInfoModalDefault = {
  visible: false,
  modelName: undefined,//型号
  category: undefined,//型号
  brandName: undefined,//型号
  machineCode: undefined,//机器编码
  serialNumber: undefined,//序列号
  storageName: undefined,//仓储区
  rackName: undefined,//货架
  status: undefined,//库存状态
  occupyChannel: undefined,//渠道占用
  orderKey: undefined,//关联叮当
  ostat: undefined,//订单状态
}
let deviceInfoModal = reactive({...deviceInfoModalDefault});

let storageRackModal = reactive({
  visible: false,
  storageId: undefined,
  storageRackId: undefined,
});
const storageRackOptionsForModal = ref([]);//货架号选项

// 重置查询条件
function resetQuery() {
  Object.assign(queryForm, queryFormDataDefault);
  storageRackOptions.value = [];
  ajaxQuery();
}

onMounted(() => {
  queryForm.keyword = route.query?.keyword || undefined;
  brandApi.queryPage({
    pageNum: 1,
    pageSize: 200
  }).then(res => {
    brandOptions.value = res.data.list;
  });
  storageAreaApi.queryPage({
    pageNum: 1,
    pageSize: 200
  }).then(res => {
    storageAreaOptions.value = res.data.list;
  });
  ajaxQuery();
});

function storageAreaChange() {
  storageRackOptions.value = [];
  queryForm.storageRackId = undefined;
  if (!queryForm.storageId) {
    return;
  }
  storageRackApi.queryPage({
    storageId: queryForm.storageId,
    pageNum: 1,
    pageSize: 200
  }).then(res => {
    storageRackOptions.value = res.data.list;
  });
}
function storageAreaChangeForModal() {
  storageRackOptionsForModal.value = [];
  storageRackModal.storageRackId = undefined;
  if (!storageRackModal.storageId) {
    return;
  }
  storageRackApi.queryPage({
    storageId: storageRackModal.storageId,
    pageNum: 1,
    pageSize: 200
  }).then(res => {
    storageRackOptionsForModal.value = res.data.list;
  });
}

function resetPageNumAjaxQuery() {
  queryForm.pageNum = 1;
  ajaxQuery();
}

// 查询
async function ajaxQuery() {
  selectedRows = [];
  selectedRowKeys.value = [];
  console.log(selectedRows)
  try {
    tableLoading.value = true;
    let responseModel = await inventoryApi.queryPage(queryForm);
    const list = responseModel.data.list;
    total.value = responseModel.data.total;
    tableData.value = list;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}

function update(record) {
  modalVisible.value = true;
  Object.assign(formData, record);
}

function hideStorageRackModal() {
  Object.assign(storageRackModal, {
    visible: false,
    storageId: false,
    storageRackId: false,
  });
  storageRackOptionsForModal.value = [];
}

function changeStorageRack() {
  if (!storageRackModal.storageId){
    return message.warn('请选择仓储区');
  }
  if (!storageRackModal.storageRackId){
    return message.warn('请选择货架');
  }
  inventoryApi.changeStorageRack(selectedRows.map(i => i.id).join(','),{
    storageId: storageRackModal.storageId,
    storageRackId: storageRackModal.storageRackId,
  }).then(() => {
    message.success('修改成功');
    ajaxQuery();
    hideStorageRackModal();
  })
}

function editRack() {
  if (!selectedRows.length) {
    return message.warn('请选择要操作的数据');
  }
  storageRackModal.visible = true;
}

function occupyChannel() {
  if (!selectedRows.length) {
    return message.warn('请选择要操作的数据');
  }
  inventoryApi.occupancyChannel(selectedRows.map(i => i.id).join(',')).then(() => {
    message.success('占用成功');
    ajaxQuery();
  })
}

function cancelOccupyChannel() {
  if (!selectedRows.length) {
    return message.warn('请选择要操作的数据');
  }
  inventoryApi.cancelOccupancyChannel(selectedRows.map(i => i.id).join(',')).then(() => {
    message.success('取消占用成功');
    ajaxQuery();
  })
}


function rowSelectionChange(keyArray, selected) {
  console.log(`selectedRowKeys: ${keyArray}`, 'selectedRows: ', selected);
  selectedRowKeys.value = keyArray;
  selectedRows = selected;
}

function onClose() {
  Object.assign(formData, formDataDefault);
  modalVisible.value = false;
  nextTick(() => {
    formRef.value.clearValidate();
  });
}

// 保存
async function save() {
  if (!formData.storageName || formData.storageName.trim() === '') {
    return message.error('请输入仓储区名称');
  }
  SmartLoading.show();
  const form = _.cloneDeep(formData)
  try {
    if (form.id) {
      await inventoryApi.update(form);
    } else {
      await inventoryApi.add(form);
    }
    message.success(`${form.id ? '修改' : '添加'}成功`);
    ajaxQuery();
    onClose();
  } catch (error) {
    smartSentry.captureError(error);
  } finally {
    SmartLoading.hide();
  }
}

function toOrderDetail(record) {
  router.push({path: '/order/order-detail', query: {id: record.orderId}});
}

function printDeviceInfo(data) {
  printerRef.value.printDeviceInfo({
    modelName: data.modelName,
    storage: data.storage,
    serialNumber: data.serialNumber,
    machineCode: data.machineCode
  });
}

function previewDevice(record) {
  inventoryApi.getDeviceInfo(record.id).then(res => {
    Object.assign(deviceInfoModal, {...res.data, visible: true})
    console.log(deviceInfoModal)
  })
}

function hideDeviceInfoModal() {
  Object.assign(deviceInfoModal, deviceInfoModalDefault)
}

function toOrderList(record) {
  router.push({path: '/order/order-list', query: {orderKey: deviceInfoModal.orderKey}});
}

</script>

<style lang="less" scoped>

</style>